package tree;

public class CountCompleteTreeNodes222 {
    public int countNodes(TreeNode root) {
        if(root==null){
            return 0;
        }
        int deep = 0;
        TreeNode temp = root;
        while (temp != null) {
            deep++;
            temp = temp.left;
        }
        int left = (int) Math.pow(2, deep - 1);
        int right = (int) Math.pow(2, deep) - 1;
        while (left <= right) {
            int mid = (left + right) / 2;

            if (search(mid, root, deep)) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return Math.min(left,right);
    }

    public boolean search(int target, TreeNode root, int deep) {
        TreeNode temp = root;
        int bit = 1 << (deep - 1);
        while (bit != 1) {
            bit = bit >> 1;
            if (bit > 0) {
                if ((target & bit) == bit) {
                    temp = temp.right;
                } else {
                    temp = temp.left;
                }
            }
        }
        return temp != null;
    }
}
